package com.itheima.health.service.impl;

import com.itheima.health.common.RedisConst;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.service.SmsService;
import com.itheima.health.service.ValicadeCodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

@Slf4j
@DubboService
public class ValicadeCodeServiceImpl implements ValicadeCodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SmsService smsService;

    @Override
    public void sendValidateCode(String businessType, String phone) {
        log.info("[短信-发送验证码]businessType:{},phone:{}", businessType, phone);
        //生成验证码
        int code = (int) (1000 + new SecureRandom().nextDouble() * 8999);
        log.info("[短信-发送验证码]code:{}", code);

        //发短信交给SmsService
        if (smsService.sendphoneMessage(businessType, phone, String.valueOf(code))) {
            //保存到缓存(redis)
            String redisKey = RedisConst.VALIDATE_CODE_PREFIX + businessType + ":" + phone;
            redisTemplate.boundValueOps(redisKey).set(String.valueOf(code), 5, TimeUnit.MINUTES);
            log.info("[查看是否存入redis]code:{}", redisTemplate.boundValueOps(redisKey).get());
        } else {
            throw new BusinessRuntimeException("请检查，连接MQ异常，短信发送失败");
        }
    }

    @Override
    public boolean checkValidateCode(String validateCodeType, String phone, String code) {
        log.info("[短信-校验验证码]type:{},phone:{},code:{}", validateCodeType, phone, code);
        String redisKey = RedisConst.VALIDATE_CODE_PREFIX + validateCodeType + ":" + phone;
        //查询redis里的值
        String expectVal = (String) redisTemplate.boundValueOps(redisKey).get();
        //对比是否匹配
        if (!StringUtils.isEmpty(expectVal) && expectVal.equals(code)) {
            //如果匹配则删除redis并返回true
            redisTemplate.delete(redisKey);
            return true;
        } else {
            //如果不匹配则返回false
            return false;
        }

    }
}
